package cfs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.form.FormBeanFactory;

import cfs.databean.Customer;
import cfs.databean.Employee;
import cfs.formbean.PasswordFormBean;
import cfs.model.CustomerDAO;
import cfs.model.EmployerDAO;
import cfs.model.Model;

/**
 * Servlet implementation class ChangePassword
 */
public class ChangePasswordAction extends Action {
	private FormBeanFactory<PasswordFormBean> formBeanFactory = FormBeanFactory
			.getInstance(PasswordFormBean.class);

	CustomerDAO userDAO;
	EmployerDAO employeeDAO;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChangePasswordAction(Model model) {
		super();
		userDAO = model.getCustomerDao();
		employeeDAO = model.getEmployerDao();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "changePassword.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {
			PasswordFormBean form = formBeanFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "ChangePassword.jsp";
			}

			errors.addAll(form.getValidationErrors());
			if (errors.size() != 0) {
				return "ChangePassword.jsp";
			}

			HttpSession session = request.getSession();

			if (session.getAttribute("employee") == null
					&& session.getAttribute("user") == null) {
				errors.add("Cannot detect user type");
				return "ChangePassword.jsp";
			}

			if (session.getAttribute("employee") != null) {
				Employee currentEmp = (Employee) session
						.getAttribute("employee");
//				EmployerDAO empDAO = new EmployerDAO();
				currentEmp.setPassword(form.getPassword());
//				empDAO.update(currentEmp);
				employeeDAO.setPassword(currentEmp.getUsername(), currentEmp.getPassword());
			}
			if (session.getAttribute("user") != null) {
				Customer currentCus = (Customer) session.getAttribute("user");
				CustomerDAO cusDAO = new CustomerDAO();
				currentCus.setPassword(form.getPassword());
				cusDAO.setPassword(currentCus.getCustomer_id(), currentCus.getPassword());
			}

			request.setAttribute("successStatement", "Password is changed");
			return "Success.jsp";
		} catch (Exception e) {
			errors.add("There is an error");
			return "ChangePassword.jsp";
		}
	}
}
